package com.bah.tract.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityHome;
import org.jboss.seam.security.Credentials;

import com.bah.tract.model.Person;
import com.bah.tract.model.Role;

@Name("personHome")
public class PersonHome extends EntityHome<Person> {
	private static final Log LOG = LogFactory.getLog(PersonHome.class);

	@In
	Credentials credentials;

	@Override
	public String persist() {
		Person person = getInstance();
		StringBuilder message = new StringBuilder();
		message.append(credentials.getUsername())
				.append(" is creating person ").append(person.getBoozAllenID())
				.append(" with roles: ");
		for (Role role : person.getRoles()) {
			message.append(role.getName());
		}
		LOG.info(message.toString());
		return super.persist();
	}

	@Override
	public String update() {
		Person person = getInstance();
		StringBuilder message = new StringBuilder();
		message.append(credentials.getUsername())
				.append(" is updating person ").append(person.getBoozAllenID())
				.append(" with roles: ");
		for (Role role : person.getRoles()) {
			message.append(role.getName());
		}
		LOG.info(message.toString());
		return super.update();
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -6995337365941771825L;
	@In(create = true)
	PersonHome personHome;

	public void setPersonId(Long id) {
		setId(id);
	}

	public Long getPersonId() {
		return (Long) getId();
	}

	@Override
	protected Person createInstance() {
		Person person = new Person();
		Role userRole = getEntityManager().find(Role.class, 1L);
		List<Role> roles = new ArrayList<Role>();
		roles.add(userRole);
		person.setRoles(roles);
		return person;
	}

	public void load() {
		if (isIdDefined()) {
			wire();
		}
	}

	public void wire() {
		getInstance();
	}

	public boolean isWired() {
		return true;
	}

	public Person getDefinedInstance() {
		return isIdDefined() ? getInstance() : null;
	}

}
